<template>
  <div class="announcements-container">
    <div class="page-header">
      <h2>公告管理</h2>
      <div class="toolbar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索公告标题"
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 10px;"
          @keyup.enter.native="filterAnnouncements">
        </el-input>
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">添加公告</el-button>
      </div>
    </div>

    <el-table :data="filteredAnnouncements" style="width: 100%" v-loading="loading">
      <el-table-column prop="announcementId" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题" width="300"></el-table-column>
      <el-table-column label="内容" show-overflow-tooltip>
        <template slot-scope="scope">
          <div class="content-preview">{{ scope.row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialog.visible" width="60%" :before-close="handleDialogClose">
      <el-form :model="announcementForm" :rules="formRules" ref="announcementForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="announcementForm.content" 
            placeholder="请输入公告内容"
            :rows="10">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllAnnouncements,
  getAnnouncementById,
  addAnnouncement,
  updateAnnouncement,
  deleteAnnouncement
} from '@/api/admin'

export default {
  name: 'AnnouncementManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      searchQuery: '',
      announcements: [],
      dialog: {
        visible: false,
        type: 'add' // 'add' 或 'edit'
      },
      announcementForm: {
        announcementId: null,
        title: '',
        content: ''
      },
      formRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.dialog.type === 'add' ? '添加公告' : '编辑公告'
    },
    filteredAnnouncements() {
      if (!this.searchQuery) {
        return this.announcements
      }
      
      const query = this.searchQuery.toLowerCase()
      return this.announcements.filter(announcement => {
        return announcement.title.toLowerCase().includes(query)
      })
    }
  },
  created() {
    this.fetchAnnouncements()
  },
  methods: {
    async fetchAnnouncements() {
      this.loading = true
      try {
        const response = await getAllAnnouncements()
        if (response.code === 200) {
          this.announcements = response.data || []
        } else {
          this.$message.error(response.message || '获取公告列表失败')
        }
      } catch (error) {
        console.error('获取公告列表出错:', error)
        this.$message.error('获取公告列表失败')
      } finally {
        this.loading = false
      }
    },
    
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    
    showAddDialog() {
      this.dialog.type = 'add'
      this.announcementForm = {
        announcementId: null,
        title: '',
        content: ''
      }
      this.dialog.visible = true
      
      this.$nextTick(() => {
        if (this.$refs.announcementForm) {
          this.$refs.announcementForm.clearValidate()
        }
      })
    },
    
    async handleEdit(announcement) {
      this.dialog.type = 'edit'
      
      try {
        const response = await getAnnouncementById(announcement.announcementId)
        if (response.code === 200) {
          this.announcementForm = {
            announcementId: response.data.announcementId,
            title: response.data.title,
            content: response.data.content
          }
          this.dialog.visible = true
          
          this.$nextTick(() => {
            if (this.$refs.announcementForm) {
              this.$refs.announcementForm.clearValidate()
            }
          })
        } else {
          this.$message.error(response.message || '获取公告详情失败')
        }
      } catch (error) {
        console.error('获取公告详情出错:', error)
        this.$message.error('获取公告详情失败')
      }
    },
    
    handleDialogClose() {
      this.dialog.visible = false
    },
    
    filterAnnouncements() {
      // 已通过计算属性filteredAnnouncements实现
    },
    
    handleSubmit() {
      this.$refs.announcementForm.validate(async valid => {
        if (!valid) return
        
        this.submitting = true
        
        try {
          if (this.dialog.type === 'add') {
            const response = await addAnnouncement({
              title: this.announcementForm.title,
              content: this.announcementForm.content
            })
            
            if (response.code === 200) {
              this.$message.success('添加公告成功')
              this.fetchAnnouncements()
              this.dialog.visible = false
            } else {
              this.$message.error(response.message || '添加公告失败')
            }
          } else {
            const response = await updateAnnouncement(
              this.announcementForm.announcementId,
              {
                title: this.announcementForm.title,
                content: this.announcementForm.content
              }
            )
            
            if (response.code === 200) {
              this.$message.success('更新公告成功')
              this.fetchAnnouncements()
              this.dialog.visible = false
            } else {
              this.$message.error(response.message || '更新公告失败')
            }
          }
        } catch (error) {
          console.error('提交公告表单出错:', error)
          this.$message.error('操作失败，请稍后重试')
        } finally {
          this.submitting = false
        }
      })
    },
    
    handleDelete(announcement) {
      this.$confirm('确定要删除该公告吗？此操作不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteAnnouncement(announcement.announcementId)
          if (response.code === 200) {
            this.$message.success('删除公告成功')
            this.fetchAnnouncements()
          } else {
            this.$message.error(response.message || '删除公告失败')
          }
        } catch (error) {
          console.error('删除公告出错:', error)
          this.$message.error('删除公告失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.announcements-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.toolbar {
  display: flex;
  align-items: center;
}

.content-preview {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 500px;
}
</style> 